import time

import cv2
import mediapipe as mp
import math



class HandDetector():
    def __init__(self, mode=False,
                maxHands=2,
                model_complexity=1,
                detectionCon=0.5,
                 trackCon=0.5):

        self.mode = mode
        self.maxHands = maxHands
        self.model_complexity = model_complexity
        self.detectionCon = detectionCon
        self.trackCon = trackCon
        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode,self.maxHands,self.model_complexity,
                                        self.detectionCon,self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils

    def findHands(self, frame, draw=True):

        imgRGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        self.results = self.hands.process(imgRGB)
        # print(results.multi_hand_landmarks)

        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(frame, handLms,
                                               self.mpHands.HAND_CONNECTIONS)
        return frame


    def findPosition(self, frame, draw=True):
        self.lmlist = []
        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                for id, lm in enumerate(handLms.landmark):
                    h, w, c = frame.shape
                    cx, xy = int(lm.x * w), int(lm.y * h)
                    self.lmlist.append([id, cx, xy])
                    if draw:
                        cv2.circle(frame, (cx, xy), 5, (255, 0, 255), cv2.FILLED)
        return self.lmlist

    def findgers(self,p1,p2,frame):
        x1, y1 = p1
        x2, y2 = p2
        cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
        cv2.circle(frame, (x1, y1), 15, (255, 0, 255), cv2.FILLED)
        cv2.circle(frame, (x2, y2), 15, (255, 0, 255), cv2.FILLED)
        cv2.line(frame, (x1, y1), (x2, y2), (255, 0, 255), 3)
        cv2.circle(frame, (cx, cy), 15, (255, 0, 255), cv2.FILLED)
        lentgh = math.hypot(x2 - x1, y2 - y1)

        return lentgh,cx,cy

def main():
    cap = cv2.VideoCapture(0)
    detector = HandDetector()
    Ptime = 0
    while True:
        ret, frame = cap.read()
        frame = detector.findHands(frame)
        Ctime = time.time()
        fps = 1 / (Ctime - Ptime)
        Ptime = Ctime
        cv2.putText(frame, f'fps:{int(fps)}', (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 255), 2)
        cv2.imshow('frame', frame)
        cv2.waitKey(45)


if __name__ == '__main__':
    main()